package com.serverlite.system.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.serverlite.framework.utils.PropertiesUtils;
import com.serverlite.system.config.AppConfig;

public class UrlFilter implements Filter{

    @Override
    public void destroy() {
    }

    @SuppressWarnings("unchecked")
    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        
        //获取当前URI
        String currentURI = request.getRequestURI().replace(request.getContextPath(), "");
        //获取要过滤的URI列表
        String filterURI = PropertiesUtils.get("sys.filter");
        //去掉回车换行及空白字符,转换成List
        List<String> filerList = Arrays.asList(filterURI.replace("\r", "").replace("\n", "").trim().split(","));
        if(filerList.contains(currentURI)){
            Map<String,Object> user = (Map<String, Object>) request.getSession().getAttribute(AppConfig.USER_SESSION_ID);
            if(user == null){
                request.getRequestDispatcher("/WEB-INF/system/login.jsp").forward(req, res);
            } else {
                chain.doFilter(req, res);
            }
        } else {
            chain.doFilter(req, res);
        }
        
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

}
